import { isIOS, actionTrack } from './utils'
import { wxOpt } from './config'
import { Dialog, Toast } from 'vant'
import { share, getWxSign, showMenuItems, hideAllNonBaseMunuItem } from '@/assets/js/wechat.js'
export const Global = {
  data () {
    return {
      timeout: null,
      load: false,
      mclr: 'rgba(24, 159, 255, 1)',
      leaveMsg: '我的留言', // 个人中心功能列表页用来控制留言消息数是否展示
      BASE_URL: process.env.VUE_APP_BASE_URL,
      VERSION: process.env.VUE_APP_VERSION,
      VIDEO_LABEL_ID: process.env.VUE_APP_VIDEO_LABEL_ID, // 我的收藏视频栏目id
      VIDEO_LABEL_CODE: process.env.VUE_APP_VIDEO_LABEL_CODE, // 我的收藏视频栏code
      PAPERID: process.env.VUE_APP_PAPERID, // 测评问卷Id
      SERVICE_PORTAL: process.env.VUE_APP_SERVICE_PORTAL, // url对应的服务前缀
      SERVICE_UPGRADE_SURVEY: process.env.VUE_APP_SERVICE_UPGRADE_SURVEY, // 新版问卷接口
      // WXAPPID: 'wxa835b0822d0aaec9', // 公众号appid 测试号-李 项目版
      WXAPPID: 'wxcb97a1ce67b41347', // 公众号appid 悦米技术服务 项目版
      SITEID: '1329635653367447553', // 微站点Id 测试号-李 项目版
      // SITEID: '1286555161249976322' // 微站点Id 悦米技术服务 项目版
      sessionId: '123', // 项目应用Id, 用于生成唯一的userId名称，存入localStorage
      KEY_USERID: `userId_123`
    }
  },
  methods: {
    // 验证手机号
    checkTel (tel) {
      let re = /^1\d{10}$/

      return re.test(tel)
      // if (result) {
      //   return true
      // } else {
      //   return false
      // }
    },
    isIOS () {
      return isIOS()
    },
    getOpenid () {
      let openid = (sessionStorage.getItem('openid') || '').trim()
      if (!openid) {
        return
      }
      return openid
    },
    getPrevRoute () {
      // 获取链接中上一个页面的路由
      let prev = this.$route.query.prev
      let arr = prev.split('?')
      let path = arr[0]
      let query = {}
      if (arr && arr.length > 1) {
        let queryStrs = prev.split('?')[1].split('&')
        queryStrs.forEach(item => {
          let arr = item.split('=')
          query[arr[0]] = arr[1]
        })
      }
      return { path: path, query: query }
    },
    shareHref () {
      if (
        isIOS() &&
        this.$route.path !== location.pathname.replace('/mobile', '')
      ) {
        return location.origin + '/mobile' + this.$route.fullPath
      }
      return location.href
    },
    _pxToRem (content) {
      if (!content) return
      let reg = /([:|(]*)(\s*)([-|+\d+.*\d+]+)(px)/g
      let str = content.replace(reg, (content, $1, space, $2) => {
        return $1 + space + parseInt($2) / 50 + 'rem'
      })
      let regPt = /([:|(]*)(\s*)([-|+\d+.*\d+]+)(pt)/g
      str = str.replace(regPt, (content, $1, space, $2) => {
        return $1 + space + ((parseInt($2) / 50) * 130) / 100 + 'rem'
      })
      // 去除DOM间的空格：解决inline-block间距问题
      let regSpace = /(>)(\s)+(<)/g
      str = str.replace(regSpace, (content, $1, space, $2) => {
        return $1 + $2
      })
      return str
    },
    // 页面加载效果
    showPageLoad (cb) {
      this.$_load.show()
      let timer = setTimeout(() => {
        if (timer) {
          clearTimeout(timer)
          timer = null
        }
        this.$_load.hide()
        if (cb && typeof cb === 'function') {
          cb()
        }
      }, 1000)
    },
    showLoad (cb) {
      this.load = true
      let timer = setTimeout(() => {
        if (timer) {
          clearTimeout(timer)
          timer = null
        }
        this.load = false
        if (cb && typeof cb === 'function') {
          cb()
        }
      }, 1000)
    },
    handleWarning (rsp) {
      if (rsp.ret === 1) {
        this.$router.replace({
          name: 'auth',
          query: { prev: this.$route.fullPath }
        })
      } else {
        this.$toast(rsp.msg)
      }
    },
    getLink (link) {
      return `${location.origin}${link.replace(location.origin, '')}`
    },
    toRoute (route) {
      this.$router.push(route)
    },
    closeWindow () {
      WeixinJSBridge.call('closeWindow') // eslint-disable-line
    },
    linkTo (name, params, query) {
      this.$router.push({
        name: name,
        params: params,
        query: query
      })
    },
    replaceTo (name, params, query) {
      this.$router.replace({
        name: name,
        params: params,
        query: query
      })
    },
    qnImg (url, w = 750, h = 420) {
      if (!url) return ''
      // let suffix = ~url.indexOf('http://qn.yuemia.com/')
      //   ? `?imageView2/1/w/${w}/h/${h}/interlace/1`
      //   : ''
      let suffix = `?imageView2/1/w/${w}/h/${h}/interlace/1`
      return suffix
    },
    copyObj (original, target) {
      let info = {}
      for (let key in original) {
        if (
          typeof target[key] === 'undefined' ||
          target[key] === null ||
          target[key] === 'undefined'
        ) {
          info[key] = original[key]
        } else {
          info[key] = target[key]
        }
      }
      return info
    },
    console (...args) {
      if (wxOpt.showConsole) {
        console.log(...args)
      }
    },
    createUniqueId () {
      return parseInt(Math.random() * 10000000) + ''
    },
    // 判断除了自定义页面外，是否需要显示浮标
    checkIfShowBouy () {
      let isUseBuoy = localStorage.getItem('useBuoy') ? localStorage.getItem('useBuoy') : '0'
      if (isUseBuoy === '1') {
        return true
      } else {
        return false
      }
    },
    // 获取不到详情，回到前一个页面
    handleErrorAndBack (e) {
      let msg = ''
      if (e.response && e.response.data) {
        msg = e.response.data.message
      }
      if (!msg) {
        msg = '连接异常，请稍后再试'
      }
      Toast.clear()
      Dialog.alert({
        message: msg
      }).then(() => {
        this.$_load.hide()
        history.go(-1)
      })
    },
    // 显示服务器返回的错误内容
    showMsgError (msg, cb) {
      this.$_load.hide()
      this.$toast({
        message: msg,
        onClose: () => {
          if (cb && typeof cb === 'function') {
            cb()
          }
        }
      })
    },
    // 判断当前用户是否认证
    checkIfAuthed () {
      let isCertification = Boolean(localStorage.getItem('isAuth'))
      if (isCertification) {
        Dialog.alert({
          message: '您还未认证，请先认证！'
        }).then(() => {
          this.$router.push({
            name: 'auth',
            query: {
              prev: this.$route.fullPath
            }
          })
        })
      }
    },
    // 格式化时间 YYYY-MM-DD HH:mm:ss
    getFormatedTime (date, split, endType) {
      let _split = split || '-'
      let year = date.getFullYear()
      let month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)
      let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      let hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      let minite = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      let second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      if (endType === 'day') {
        return year + _split + month + _split + day
      } else if (endType === 'second') {
        return year + _split + month + _split + day + ' ' + hour + ':' + minite + ':' + second
      } else if (endType === 'hour-minute') {
        return hour + ':' + minite
      } else if (endType === 'hour-second') {
        return hour + ':' + minite + ':' + second
      } else {
        return year + _split + month + _split + day + ' ' + hour + ':' + minite
      }
    },
    // 格式化评论时间
    formatCommentTime (time) {
      if (typeof time === 'string') {
        time = time.replace(/-/g, '/')
      }
      console.log('formatCommentTime: ', time)
      let timeDate = new Date(time)
      let nowDate = new Date()
      let diffSeconds = (nowDate.getTime() - timeDate.getTime()) / 1000
      if (diffSeconds < 3600) {
        return parseInt(diffSeconds / 60) + '分钟前'
      } else if (diffSeconds < (3600 * 24)) {
        return parseInt(diffSeconds / 3600) + '小时前'
      } else if (diffSeconds < (3600 * 24 * 7)) {
        return parseInt(diffSeconds / (3600 * 24)) + '天前'
      } else if (diffSeconds < (3600 * 24 * 30)) {
        return parseInt(diffSeconds / (3600 * 24 * 7)) + '周前'
      } else if (diffSeconds < (3600 * 24 * 30 * 6)) {
        return parseInt(diffSeconds / (3600 * 24 * 30)) + '个月前'
      } else if (diffSeconds < (3600 * 24 * 30 * 12)) {
        return '半年前'
      } else {
        return parseInt(diffSeconds / (3600 * 24 * 30 * 12)) + '年前'
      }
    },
    handleError (e) {
      let str = e.data + ''
      if (!window.errTimer) {
        window.errTimer = setTimeout(() => delete window.errTimer, 1000)
        if (e.response && e.response.data && e.response.data.message) {
          this.$toast({
            message: e.response.data.message
          })
        } else {
          if (str.search('timeout') !== -1) {
            // 超时error捕获
            this.$toast('请求超时,请稍后重试~')
          } else if (e.status === 400) {
            this.$toast('无效的请求')
          } else if (e.status === 403) {
            this.$toast(e.data.message || '没有权限')
          } else if (e.status === 401) {
            this.$toast('未认证')
          } else if (e.status === 404) {
            this.$toast('找不到服务器，请稍后再试')
          } else if (e.status === 503) {
            this.$toast('服务暂时无法访问！')
          } else if (e.status === 5003) {
            this.$router.push({ name: 'notFound' })
          } else if (e.status === 500) {
            this.$toast(e.data.message)
          } else {
            this.$toast(e.message)
          }
        }
      }
    },
    // 判断订阅号，在没有获取openid的前提下，该如何操作
    checkIfGotOpenid (validCb, inValidCb, finallyCb) {
      // 如果设置， 始终都会执行的函数
      if (finallyCb && typeof finallyCb === 'function') {
        finallyCb()
      }
      // 开始判断
      let openid = sessionStorage.getItem('openid')
      let wechatInfo = JSON.parse(localStorage.getItem('wechatInfo'))
      let hasExpand = wechatInfo.hasExpand || false
      let expandAppid = wechatInfo.expandAppid || ''
      let wechatType = wechatInfo.wechatType
      if (!openid) {
        // 调用，没有openid时的逻辑
        if (inValidCb && typeof inValidCb === 'function') {
          inValidCb()
        }
        // 首先判断是否是通过订阅号，拿过openid，重定向回来的
        if (this.$route.query.redirect || this.$route.query.isSubscribe) {
          // 直接跳二维码
          window.eventBus.$emit('showWechatQr')
          return false
        }
        let siteId = localStorage.getItem('siteId')
        let appid = sessionStorage.getItem('appid')
        let tenantId = localStorage.getItem('tenantId')
        // 如果当前是订阅号
        if (wechatType === '1') {
          // 如果订阅号已经选择升级, 则调用服务号授权
          if (hasExpand && expandAppid) {
            // 重定向的前端地址
            let targetUrl = ''
            if (location.href.indexOf('?') === -1) {
              targetUrl = `${location.href}?tenantId=${localStorage.getItem('tenantId')}`
            } else {
              targetUrl = location.href
            }
            let redirectUri = encodeURIComponent(targetUrl)
            // 拿到code后，需要重定向的后端接口地址
            let encodedRedirectUri = encodeURIComponent(`${location.origin}/platform/wechat/server/response/user_info?expandAppid=${appid}&tenantId=${tenantId}&redirect_target=${redirectUri}`)
            // 调用微信网页授权的地址
            let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${expandAppid}&redirect_uri=${encodedRedirectUri}&response_type=code&scope=snsapi_userinfo&state=${tenantId}&component_appid=wx91665755fce8d3df#wechat_redirect`
            console.log('=== url ===: ', url)
            location.href = url
          } else {
            this.$toast({
              message: '请联系服务方，提升订阅号运营能力！',
              duration: 3000
            })
          }
        // 服务号授权
        } else {
          let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(location.origin).toLowerCase()}%2fplatform%2fwechat%2fserver%2fresponse%2fto_wechat_web%3ftenantId%3d${tenantId}%26siteId%3d${siteId}%26pageName%3d1285531171492466690%26target_redirect%3d${encodeURIComponent(location.origin).toLowerCase()}${encodeURIComponent(this.BASE_URL).toLowerCase()}%2fhome&response_type=code&scope=snsapi_base&state=123&component_appid=wx91665755fce8d3df#wechat_redirect`
          location.href = url
        }
      // 如果有openid，继续后面的逻辑
      } else {
        if (validCb && typeof validCb === 'function') {
          validCb()
        }
      }
    },
    // 判断当前用户是否关注了公众号/订阅号
    checkIfSubscribe () {
      if (localStorage.getItem('isSubscribe')) {
        return Number(localStorage.getItem('isSubscribe'))
      } else {
        return 0
      }
    },
    // 用户操作数据埋点
    userActionTrack (data = {}) {
      actionTrack(data)
    },
    // 在详情页检查当前知识对象，是否需要认证信息，或者身份类型匹配，才能查看
    checkVisitTypeInDetail (visitType, knowledgeType) {
      // 如果设置了具体的用户类型权限
      if (visitType && visitType[0] && visitType[0] !== '-1') {
        let userType = localStorage.getItem('userType') || '-1'
        // 如果当前用户未认证
        if (this.$route.query.openid === 'unsubscribe') {
          window.eventBus.$emit('showWechatQr')
        } else {
          // 获取知识内容的限制类型
          let visitTypeStr = ''
          visitType.forEach(item => {
            switch (item) {
              case '1': visitTypeStr += '员工/'; break
              case '2': visitTypeStr += '医生/'; break
              case '3': visitTypeStr += '患者/'; break
            }
          })
          visitTypeStr = visitTypeStr.slice(0, visitTypeStr.length - 1)
          // 获取操作类型
          let action = ''
          switch (knowledgeType) {
            case 'article': action = '浏览'; break
            case 'live': action = '观看'; break
            case 'openClass': action = '观看'; break
            default: action = '观看'
          }
          if (userType === '-1') {
            localStorage.setItem('authBackHref', location.href)
            window.eventBus.$emit('showAuthGuide', visitTypeStr + action)
          // 如果当前用户已认证
          } else {
            // 如果认证类型与用户权限不匹配
            if (!visitType.filter(item => item === userType)[0]) {
              window.eventBus.$emit('showNotMatch', visitTypeStr + action)
            }
          }
        }
      }
    },
    // 在列表页检查当前知识对象， 如果用户认证信息与知识内容权限不匹配，直接弹出不匹配
    checkVisitTypeInList (visitType, knowledgeType, cb) {
      let userType = localStorage.getItem('userType') || '-1'
      if (userType !== '-1' && visitType && visitType[0] && visitType[0] !== '-1') {
        // 如果不匹配
        if (!visitType.filter(item => item === userType)[0]) {
          // 获取知识内容的限制类型
          let visitTypeStr = ''
          visitType.forEach(item => {
            switch (item) {
              case '1': visitTypeStr += '员工/'; break
              case '2': visitTypeStr += '医生/'; break
              case '3': visitTypeStr += '患者/'; break
            }
          })
          visitTypeStr = visitTypeStr.slice(0, visitTypeStr.length - 1)
          // 获取操作类型
          let action = ''
          switch (knowledgeType) {
            case 'article': action = '浏览'; break
            case 'live': action = '观看'; break
            case 'openClass': action = '观看'; break
            default: action = '观看'
          }
          this.$toast(`本内容只允许${visitTypeStr}${action}`)
          return false
        }
      }
      if (cb && typeof cb === 'function') {
        cb()
      }
    },
    handleIntegralError (e) {
      let str = e + ''
      if (e.toString() === 'Cancel') {
        console.log('handleIntegralError: 请求已取消！')
        return
      }
      let msg = `请求无响应，请稍后再试`
      if (str.search('timeout') !== -1) {
        msg = '请求超时，请稍后再试'
      } else if (~str.search('Network Error')) {
        msg = '请检查您的网络'
      }
      if (e.response && e.response.data) {
        msg = e.response.data.message
      }
      if (!msg) {
        msg = '连接异常，请稍后再试'
      }
      console.log('handleIntegralError: ', msg)
    },
    // 初始化Localstorage中的个人信息
    initCacheUserInfo () {
      localStorage.setItem('isSubscribe', 0)
      localStorage.setItem('fansAvatar', '')
      localStorage.setItem('fansNickName', '')
      localStorage.setItem('userName', '')
      localStorage.setItem('userType', -1)
      localStorage.setItem('userId', '')
    },
    // 根据 target的字段，从origin中更新 target对应的字段
    assignKey (target, origin) {
      if (!target || !origin) {
        return false
      }
      for (let targetKey of Object.keys(target)) {
        if (origin.hasOwnProperty(targetKey)) {
          target[targetKey] = origin[targetKey]
        }
      }
    },
    // 判断是否是微信环境
    checkIfWxClient () {
      var ua = navigator.userAgent.toLowerCase()
      let matchArr = ua.match(/MicroMessenger/i)
      // console.log('ua: ', ua)
      // console.log('ua.match(/MicroMessenger/i): ', matchArr)
      if (matchArr && matchArr.filter(item => item === 'micromessenger')[0]) {
        return true
      }
      return false
    },
    /**
     * 微信工具菜单显隐，并设置分享
     * @param showAllMenu 是否需要显示所有工具菜单
     * @param showMenuList 需要显示的工具菜单数组, 默认为只有分享菜单
     * @param forbitShare 是否禁止分享
     * @param shareInfo 分享配置参数对象, title、desc、link、imgUrl
     */
    setWxToolMenuAndShare ({
      showAllMenu = false,
      showMenuList = [ 'menuItem:share:appMessage', 'menuItem:share:timeline' ],
      forbitShare = false,
      shareInfo
    }) {
      // 初始化默认分享配置项
      let _shareInfo = {
        title: '问卷调研',
        desc: '',
        link: location.href,
        imgUrl: 'https://dev-pro.oss.yuemia.com/202105191042210022.png'
      }
      // 如果传入新的配置项，则更新对应配置项
      if (shareInfo) {
        this.assignKey(_shareInfo, shareInfo)
      }
      // 检查分享链接，确保带上sessionId参数, 并且去除openid参数
      let link = _shareInfo.link
      link = link.replace(/&?(openid|appid|redirect|ssid)=[^&]+/g, '')
      if (!/sessionId=\w+/.test(link)) {
        let stepIndex = link.indexOf('sessionId=')
        // 如果sessionId参数值是空，补上值
        if (stepIndex !== -1) {
          link = link.slice(0, stepIndex + 10) +
                 sessionStorage.getItem('sessionId') +
                 link.slice(stepIndex + 10)
        // 如果没有sessionId参数，补上全部参数
        } else {
          let newParam = `sessionId=${sessionStorage.getItem('sessionId')}`
          if (/^[^?]*$/.test(link)) {
            link += `?${newParam}`
          } else if (/^\S+\?\S+$/.test(link)) {
            link += `&${newParam}`
          } else if (/^\S+\?$/.test(link)) {
            link += newParam
          }
        }
      }
      _shareInfo.link = link
      // console.log('showAllMenu: ', showAllMenu)
      // console.log('showMenuList: ', showMenuList)
      // console.log('forbitShare: ', forbitShare)
      console.log('_shareInfo: ', _shareInfo)
      // 如果显示所有工具菜单
      if (showAllMenu) {
        // 如果可以分享，则设置分享信息
        if (!forbitShare) {
          getWxSign(wx => {
            share(_shareInfo, wx)
          })
        }
      // 否则，先隐藏所有工具菜单
      } else {
        getWxSign(wx => {
          hideAllNonBaseMunuItem(wx, () => {
            // 再显示指定工具菜单
            showMenuItems(wx, showMenuList, () => {
              // 如果可以分享，展示分享工具菜单，并设置分享信息
              if (!forbitShare) {
                share(_shareInfo, wx)
              }
            })
          })
        })
      }
    },
    /**
     * 根据运行环境，拦截用户操作
     * 1. 微信环境，如果用户没有关注，需要弹出引导关注二维码
     * 2. 非微信环境，如果没有用户的userId，需要弹出引导注册弹框
     */
    checkAuth (cb) {
      // 如果是微信环境
      if (this.checkIfWxClient()) {
        // 如果用户没有关注，则弹出二维码
        if (this.checkIfSubscribe() !== 1) {
          window.eventBus.$emit('showWechatQr')
        } else {
          if (cb && typeof cb === 'function') {
            cb()
          }
        }
      // 如果是非微信环境
      } else {
        // 如果没有用户的 userId, 则弹出注册引导框
        if (!localStorage.getItem(this.KEY_USERID)) {
          window.eventBus.$emit('showRegisterGuide')
        } else {
          if (cb && typeof cb === 'function') {
            cb()
          }
        }
      }
    },
    /**
     * 竖向滚动 DOM到指定的位置
     * @param el 需要竖向滚动的元素
     * @param targetTop 指定的scrollTop值
     * @param stepTop 每次滚动的距离
     **/
    scrollDOM (el, targetTop, stepTop) {
      let currTop = el.scrollTop
      let scroll = () => {
        if (Math.abs(targetTop - currTop) > stepTop) {
          if (targetTop > currTop) {
            currTop += stepTop
          } else {
            currTop -= stepTop
          }
          el.scrollTop = currTop
          return requestAnimationFrame(scroll)
        } else {
          el.scrollTop = targetTop
        }
      }
      scroll()
    }
  }
}
export const CheckForm = {
  methods: {
    // 验证邮箱
    checkEmail (email) {
      /* eslint-disable no-useless-escape */
      let re = /\w+((-w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+/

      return re.test(email)
      // if (result) {
      //   return true
      // } else {
      //   return false
      // }
    },
    // 验证验证码长度
    checkCode (val) {
      return val.length === 4
    },
    // 验证是否为空
    checkEmpty (obj, exclude) {
      for (let key in obj) {
        if (exclude && exclude.indexOf(key) !== -1) {
          continue
        }
        if (obj[key] === null || obj[key] === undefined) {
          return false
        }
        if (obj[key].constructor === Array && obj[key].length === 0) {
          return false
        }
        if (obj[key] === '') {
          return false
        }
      }
      return true
    }
  }
}
